/**
 * Copyright (c) 2016-2019 人人开源 All rights reserved.
 *
 * https://www.renren.io
 *
 * 版权所有，侵权必究！
 */

package com.example.common.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.type.TypeReference;
import lombok.SneakyThrows;
import org.apache.http.HttpStatus;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Objects;

/**
 * 返回数据
 *
 * @author Mark sunlightcs@gmail.com
 */
public class R extends HashMap<String, Object> {

    public final static int DEFAULT_CODE = 0;

	private static final long serialVersionUID = 1L;
	
	public R() {
		put("code", DEFAULT_CODE);
		put("msg", "success");
	}

	@SneakyThrows
	public  <T> T getData(String key, Class<T> clazz){
        Object data = this.get(key);
        if (data == null) {
            return null;
        }
        if (data.getClass() == clazz) {
            String jsonData = String.valueOf(data);
            return JSONObject.parseObject(jsonData, clazz);
        }
        else if (data.getClass() == LinkedHashMap.class){
            LinkedHashMap<String, Object> map = (LinkedHashMap) data;
            return JSONObject.parseObject(JSONObject.toJSONString(map), clazz);
        }
        else if (data.getClass() == String.class) {
            String str = (String) data;
            return JSONObject.parseObject(str, clazz);
        }
        else {
            return clazz.newInstance();
        }
    }

	@SneakyThrows
	public  <T> T getData(TypeReference<T> reference){
        return JacksonUtils.json2List(this.get("data"), reference);
    }


    public R setData (Object data) {
	    this.put("data", data);
	    return this;
    }

	
	public static R error() {
		return error(HttpStatus.SC_INTERNAL_SERVER_ERROR, "未知异常，请联系管理员");
	}
	
	public static R error(String msg) {
		return error(HttpStatus.SC_INTERNAL_SERVER_ERROR, msg);
	}
	
	public static R error(int code, String msg) {
		R r = new R();
		r.put("code", code);
		r.put("msg", msg);
		return r;
	}

	public static R ok(String msg) {
		R r = new R();
		r.put("msg", msg);
		return r;
	}
	
	public static R ok(Map<String, Object> map) {
		R r = new R();
		r.putAll(map);
		return r;
	}
	
	public static R ok() {
		return new R();
	}

	public R put(String key, Object value) {
		super.put(key, value);
		return this;
	}

	public int getCode () {
	    return (Integer) get("code");
    }
}
